<?php
/**
 * 体检机构
 *
 * User: kaikaic
 * Date: 2018/10/24
 * Time: 0:21
 */

namespace app\exam\controller;

use app\exam\model\SyncMecModel;
use app\exam\service\CityService;
use app\exam\service\MecService;
use controller\BasicAdmin;
use service\ConfigService;
use service\ToolsService;
use think\Db;

class Mec extends BasicAdmin {

    protected $table = "ExamMec";

    protected $categoryKey = "mec";

    public function index() {
        $this->title = "体检机构";

        $query = array();
        $query['name'] = $this->request->get("name");
        $query['status'] = intval($this->request->get("status"));

        $db = Db::name($this->table);
        if ($query['name']) {
            $db->whereLike("name", "%{$query['name']}%");
        }
        if ($query['status']) {
            $db->where(['status'=>$query['status']]);
        }
        $db = Db::name($this->table)->order('sort desc,id asc');
        return parent::_list($db, true);
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);
        $cfgMecStatus = ConfigService::cfgMecStatus();
        $category = $this->readCategoryConfig();

        for ($i=0; $i<$size; $i++) {
            $data[$i]['category'] = $category[$data[$i]['category_id']];
            $data[$i]['status_txt'] = $cfgMecStatus[$data[$i]['status']];
        }

        $this->assign('cfg_status', $cfgMecStatus);
    }

    /**
     * 添加-体检中心
     */
    public function add() {
        if ($this->request->isGet()) {
            return view('form', [
                'title'=>'新增体检机构',
                'tagsArr'=>array(),
                'image'=>ConfigService::defaultImage(),
                'category'=>$this->readCategoryConfig(),
                'type_list'=>ConfigService::cfgRegionActivityType(),
                'tags_list'=>ConfigService::mecTags(),
                'area_list'=>json_encode(CityService::getInstance()->listCityArray())
            ]);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->doInsertAction($data)) {
                $this->showSuccess('添加成功！', '/exam/mec/index');
            }else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 编辑-体检中心
     */
    public function edit() {
        $category = $this->readCategoryConfig();

        if ($this->request->isGet()) {
            $id = $this->request->get('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $mec = MecService::getInstance()->find($id);
            if (empty($mec)) {
                $this->error('记录不存在，请重新操作!');
            }
            $tagsArr = explode(',',$mec['tags']);
            $photos = array();
            $photos = explode('|',$mec['photos']);
            return view('form', [
                'title'=>'编辑体检机构',
                'vo'=>$mec,
                'category'=>$category,
                'photos'=>$photos,
                'tags_list'=>ConfigService::mecTags(),
                'tagsArr'=>$tagsArr,
                'image'=>ConfigService::defaultImage(),
                'area_list'=>json_encode(CityService::getInstance()->listCityArray())
            ]);
        }

        if ($this->request->isPost()) {
            $id = $this->request->post('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->showSuccess('编辑成功！', '/exam/mec/index');
            }else {
                $this->error('编辑失败，请稍候再试！');
            }
        }
    }

    /**
     * 删除-体检中心
     */
    public function cancel() {
        $id = intval($this->request->post('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $mec = MecService::getInstance()->find($id);
        if (empty($mec)) {
            $this->error('记录不存在，请重新操作!');
        }

        $result = MecService::getInstance()->update(array('status'=>2), $id);
        if ($result) {
            $this->success('删除成功!', '');
        }else {
            $this->error('删除失败，请重新再试!');
        }
    }

    public function map() {
        $lng = $this->request->get("lng", "");
        $lat = $this->request->get("lat", "");

        return view('map', ['title' => '设置坐标', 'lng'=>$lng, 'lat'=>$lat]);
    }

    /**
     * 数据写入
     */
    protected function doInsertAction($data) {
        if (!$data['name']) {
            return false;
        }

        if (isset($data['tags'])) {
            $data['tags'] = implode(',',$data['tags']);
        }else {
            $data['tags'] = "";
        }

        $id = isset($data['id']) ? $data['id'] : 0;
        $data['unique_code'] = strtoupper($data['unique_code']);
        if (!$this->filterEmc($data['unique_code'], $id)) {
            return false;
        }

        if (empty($data['id'])) {
            $data['sort'] = MecService::getInstance()->getMaxSort() + 1;
            $data['status'] = 1;
            $data['logo'] = $this->request->domain().$data['logo'];
            $data['create_time'] = time();

            $result = $id = Db::name($this->table)->insertGetId($data);
        } else {
            $id = intval($data['id']);
            unset($data['id']);
            if(strstr($data['logo'],'http')){

            }else{
                $data['logo'] = $this->request->domain().$data['logo'];
            }
            $result = Db::name($this->table)->where('id', $id)->update($data);
        }

        return $result;
    }

    /**
     * 体检中心编号唯一性检查
     * id=0,表示插入, id=xx，表示更新,如果找到的记录和ID是同一记录表示可写入
     *
     * @param $uniqueCode
     * @return boolean
     */
    private function filterEmc($uniqueCode, $id) {
        if (!$uniqueCode) {
            return false;
        }

        $record = MecService::getInstance()->single(array('unique_code'=>$uniqueCode));
        if ($record) {
            if (!$id) {
                return false;
            }else if ($id != $record['id']) {
                return false;
            }
        }

        return true;
    }
}

